package net.zjitc.tree;

public class BTree {
    TreeNode<Integer> root;
    public void add(Integer value){
        if (root == null){
            root = new TreeNode<>(value);
            return;
        }
        //怎么做？
        TreeNode<Integer> currentNode = root;
        while (true){
            if (value > currentNode.data){//向右走
                if (currentNode.right == null){ //右孩子为空，直接添加为右孩子
                    currentNode.right = new TreeNode<>(value);
                    return;
                }
                currentNode = currentNode.right; //为下一次比较做准备
            }else if (value < currentNode.data){ //向左走
                if (currentNode.left == null){
                    currentNode.left = new TreeNode<>(value);
                    return;
                }
                currentNode = currentNode.left;
            }else { //相等，直接返回，不添加
                return;
            }
        }
    }

    /**
     *  功能：在二叉排序树中查找key
     * @param key 要查找 的数
     * @return true: 查找成功  false 查找失败
     */
    public boolean search(int key){
        TreeNode<Integer> currentNode = root;
        while (true){
            if (currentNode==null){
                return false;//查找失败
            }
            if (currentNode.data == key){
                return true; //查找成功
            }

            if (key > currentNode.data){ //往右找
                currentNode = currentNode.right;
            }else {  //往左找
                currentNode = currentNode.left;
            }
        }
    }

}
